package com.syni.mdd.yhd.common.all.utils;

import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Log4j2
public class Upload {
    private static AtomicInteger atomicInteger = new AtomicInteger(1);
    //视频上传地址
    private static String uploadVideoAddress;
    //商家文件上传地址
    private static String uploadBusinessAddress;
    //上传地址类型选择
    private static Map<Integer,String> imgFileMap = new HashMap<>();
    static {
        imgFileMap.put(1,"userHead/");
        imgFileMap.put(100,"logo/");
        imgFileMap.put(101,"idCard/");
        imgFileMap.put(102,"businessLicense/");
        imgFileMap.put(103,"identityProof/");
        imgFileMap.put(104,"groupBuy/");
    }

    @Value("${app.upload.video.path}")
    public void setUploadAddress(String uploadVideoAddress) {
        Upload.uploadVideoAddress = uploadVideoAddress;
    }

    @Value("${app.upload.business.path}")
    public void setUploadBusinessAddress(String uploadBusinessAddress) {
        Upload.uploadBusinessAddress = uploadBusinessAddress;
    }

    public static String getUploadVideoAddress() {
        return uploadVideoAddress;
    }

    public static String getUploadBusinessAddress() {
        return uploadBusinessAddress;
    }

    public static String uploadImg(CommonsMultipartFile imgFile, HttpServletRequest request){
        String filename[] = imgFile.getOriginalFilename().split("\\.");
        filename[0] = Base64.encodeBase64String(filename[0].getBytes());
        filename[0] = filename[0].substring(0,filename[0].length()-2);
        String path= request.getServletContext().getRealPath("/")+"aupload/"+new Date().getTime()+filename[0]+"."+filename[1];
        File newFile = new File(path);
        try {
            imgFile.transferTo(newFile);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
        String tempPath = path.substring(path.indexOf("aupload"));
        return tempPath;
    }

    public static String uploadImg2(MultipartFile multipartFile, HttpServletRequest request){
        //项目路径
        String rootURL = request.getServletContext().getRealPath("/");

        //获取后缀
        String[] suffix = multipartFile.getOriginalFilename().split("\\.");
        //获取后缀格式
        String endFile = suffix[suffix.length - 1];
        //文件具体路径
        String filePath = String.format("%supload/%s.%s",rootURL,System.currentTimeMillis(),endFile);

        //打开路径文件
        File newFile = new File(filePath);

        //上传文件
        try {
            multipartFile.transferTo(newFile);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }

        return filePath;
    }


    public static String uploadImgFile(MultipartFile multipartFile,Integer fileType){
        String filePrefix = "default/";
        if(imgFileMap.containsKey(fileType)) {
            filePrefix = imgFileMap.get(fileType);
        }
        String uploadAddress = uploadBusinessAddress + "/" + filePrefix;
        File file = new File(uploadAddress);
        if(!file.exists()){
            file.mkdirs();
        }
        Date date = new Date();
        String nowTime = DateTimeUtils.converDateToString(date, DateTimeUtils.DATE_PATTERN_DAY_01);
        String dirName = uploadAddress + "/" +  nowTime;
        //打开文件夹/创建文件夹
        File dirFile = new File(dirName);
        if(!dirFile.exists()){
            synchronized (Upload.class){
                if(!dirFile.exists()){
                    dirFile.mkdirs();
                }
            }
        }
        String resultUrl;
        try {
            int autoCount = atomicInteger.getAndIncrement();
        //回调URL
        resultUrl = filePrefix + nowTime + "/" + DateTimeUtils.converDateToString(date,DateTimeUtils.DATE_PATTERN_TIMESTAMP_03)+
                "_" + autoCount + "." + multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
        String filePath = uploadBusinessAddress + "/" + resultUrl;
        //打开需要写的文件
        File toFile = new File(filePath);
        multipartFile.transferTo(toFile);
        } catch (IOException e) {
            resultUrl = "";
            log.error("upload error",e);
        }
        return resultUrl;
    }

    public static String uploadVideo(MultipartFile multipartFile){
        //获取当前时间
        Date date = new Date();
        String resultUrl;
        String filePath;
        try {
            int autoCount = atomicInteger.getAndIncrement();
            //回调URL
            resultUrl = DateTimeUtils.converDateToString(date,DateTimeUtils.DATE_PATTERN_TIMESTAMP_03)+
                    "_" + autoCount + "." + multipartFile.getOriginalFilename().split("\\.")[1];
            filePath = uploadVideoAddress + "/" + resultUrl;
            //打开需要写的文件
            File toFile = new File(filePath);
            multipartFile.transferTo(toFile);
        } catch (IOException e) {
            filePath = "";
            log.error(e.getMessage(),e);
        }
        return filePath;
    }
}
